<template>
  <!-- 仓库 -->
  <pageTabelLayout>
    <template #pageHeader>
      <div class="my-header">
        <div class="search-form isheader" v-if="headerShow">
          <div>
            <a-form size="mini" :model="queryData" layout="inline">
              <a-form-item label="所属公司" field="firm">
                <a-cascader
                  v-model="queryData1.firm"
                  :options="gsDatas"
                  allow-clear
                  class="bacClass"
                  @change="queryClearChange"
                  :style="{ width: '200px' }"
                  popup-container="html"
                />
              </a-form-item>
              <a-form-item label="仓库名称">
                <a-select
                  popup-container="html"
                  class="bacClass"
                  :style="{ width: '160px' }"
                  :loading="loading"
                  :filter-option="false"
                  allow-search
                  v-model.trim="queryData1.warehouseName"
                  @click="handleSearchs"
                  allow-clear
                >
                  <a-option v-for="item in pageData.warehouseName" :value="item.warehouseName"
                    >{{ item.warehouseName }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-form>
          </div>
          <div class="my-tool-bar">
            <Toolbar
              :items="[
                `${permissionStore.hasPermisson('ck.cx') ? '查询' : ''}`,
                `${permissionStore.hasPermisson('ck.xz') ? '新增' : ''}`,
                `${permissionStore.hasPermisson('ck.sc') ? '删除' : ''}`,
                `${permissionStore.hasPermisson('ck.dc') ? '导出' : ''}`,
              ]"
              @add="addHandler"
              @del="deleteHandler"
              @select="selectHandler"
              @export="exports"
              @cshck="cshck"
            >
            </Toolbar>
          </div>
        </div>
        <div class="my-divisders">
          <a-divider orientation="center">
            <icon-double-up
              v-if="headerShow"
              @click="headerShow = false"
              :strokeWidth="2"
              :size="18"
            />
            <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
          </a-divider>
        </div>
      </div>
      <div class="gang"></div>
    </template>

    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" style="width: 100%; height: 100%">
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          :localeText="localeText1"
          :suppressDragLeaveHidesColumns="true"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: calc(100% - 45px)"
          @columnResized="onColumnResized"
          @columnMoved="onColumnMoved"
          @columnVisible="onColumnVisible"
          :defaultColDef="defaultColDef"
          class="ag-theme-alpine"
          :rowData="table.dataList"
          :columnDefs="tc"
        ></AgGridVuesCopys>
        <paginationCopys
          :page-size-options="pagingList1"
          :page-size="size"
          :current="page"
          :total="total"
          show-total
          show-jumper
          show-page-size
          @change="PageSize"
          @page-size-change="change1"
          style="justify-content: center"
        />
      </a-spin>
    </template>
    <a-drawer
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="sideNo"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <!-- 所属工厂 仓库名称 联系人 联系电话 地址 -->
        <a-form ref="formRef" :model="dataForm">
          <a-form-item
            label="所属公司"
            field="firmId"
            :rules="[{ required: true, message: '公司必填' }]"
            label-col-flex="120px"
          >
            <a-cascader
              :disabled="pageData.sideTitle == '修改仓库'"
              v-model="dataForm.firmId"
              :options="gsDatas2"
              allow-clear
              class="bacClass"
              @click="getAllActiveCompany2"
              @change="getAllActiveCompanys"
              ref="casOb"
              popup-container="html"
            />
          </a-form-item>
          <a-form-item
            label="仓库类型"
            field="tg"
            :rules="[{ required: true, message: '类型必填' }]"
            label-col-flex="120px"
          >
            <a-select popup-container="html" class="bacClass" v-model="dataForm.tg">
              <a-option
                v-for="(item, Index) in cklxTable"
                :key="Index"
                :value-key="Index"
                :label="item.typeName"
                :value="item.typeName + '-' + item.id"
              ></a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="编号"
            field="warehouseCode"
            :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
            label-col-flex="120px"
          >
            <a-input
              class="bacClass"
              placeholder=""
              @blur="inputBlur"
              v-model.trim="dataForm.warehouseCode"
            />
          </a-form-item>
          <a-form-item
            label="仓库名称"
            field="warehouseName"
            :rules="[{ required: true, message: '仓库名称必填' }]"
            :validate-trigger="['change', 'blur']"
            label-col-flex="120px"
          >
            <a-input class="bacClass" placeholder="" v-model.trim="dataForm.warehouseName" />
          </a-form-item>
          <a-form-item
            label="计价方式"
            field="pricingWay"
            :rules="[{ required: true, message: '计价方式必填' }]"
            label-col-flex="120px"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              v-model.trim="dataForm.pricingWay"
              @click="jjFdsFun"
            >
              <a-option v-for="item in jjFds">{{ item.detailName }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="库存警戒" field="inventoryAlert" label-col-flex="120px">
            <a-input-number class="bacClass" v-model="dataForm.inventoryAlert" :precision="0" />
          </a-form-item>
          <a-form-item label="吨料存放成本/日" field="depositCost" label-col-flex="120px">
            <a-input-number class="bacClass" v-model="dataForm.depositCost" :precision="2" />
          </a-form-item>
          <a-form-item label-col-flex="120px" label="销售仓库" field="unit">
            <a-select
              popup-container="html"
              class="bacClass"
              v-model="dataForm.salesWarehouseId"
              @focus="selDictAll"
              allow-clear
              allow-search
              :filter-option="false"
            >
              <a-option v-for="item in pageData.UnitList" :key="item.id" :value="item.detailNameEn"
                >{{ item.detailName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="备注" field="remark" label-col-flex="120px">
            <a-textarea
              class="bacClass"
              v-model.trim="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
    <ModalDialog :mask-closable="false" ref="qrModal" title="仓库二维码" @confirm="gbModal">
      <template #content>
        <a-space direction="vertical">
          <a-button type="primary" @click="print">打印</a-button>
          <div id="settings" style="width: 500px">
            <QrcodeVue :value="qrData.code"></QrcodeVue>
            <div style="display: inline-block; vertical-align: top; margin-left: 15px">
              <div style="width: 300px">公司：{{ qrData.gcName }}</div>
              <div style="width: 300px">仓库编号：{{ qrData.ckCode }}</div>
              <div style="width: 300px">仓库类型：{{ qrData.ckType }}</div>
              <div style="width: 300px">仓库名称：{{ qrData.ckName }}</div>
              <div style="width: 300px">计价方式：{{ qrData.jsjia }}</div>
            </div>
          </div>
        </a-space>
      </template>
    </ModalDialog>
  </pageTabelLayout>
</template>

<script lang="ts">
  import axios from 'axios'
  import { get, post } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import QrcodeVue from 'qrcode.vue'
  import printJS from 'print-js'
  import { ModalDialogType } from '@/types/components'
  import { ref, reactive, onMounted, toRefs, defineComponent } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import ModalDialog from '@/components/ModalDialog.vue'
  
  import { localeText } from '@/api/aggridZw'
  import usePermission from '@/store/modules/permission'
  import { pagingList } from '@/api/paging'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
  import { slicing } from '@/utils/caseFrimAndSecRig'
  interface Firm {
    name: string
    id: number
  }

  interface Cloth {
    code: string
  }

  interface WarehouserSrttingsInfo {
    id: any
    firm: any
    warehouseCode: any
    warehouseName: any
    pricingWay: any
    remark: any
    deleteState: any
    createName: any
    createTime: any
    updateName: any
    updateTime: any
    obsoleteState: any
    warehouseTypeName: any
    extendCode: any
    warehouseTypeId: any
    tg: any
    firmName: any
    firmId: Number
    salesWarehouseId: any
  }

  interface dataListType {
    shelveName: any
    shelveCode: any
    storageName: any
    storageCode: any
  }

  export default {
    name: 'WarehouseSettings',
    setup() {
      const permissionStore: any = usePermission()
      const total = ref(10)
      const page = ref(1)
      const size = ref(10)
      function PageSize(val: any) {
        page.value = val
        doRefresh()
      }
      function change1(val: any) {
        size.value = val
        doRefresh()
      }
      function doRefresh() {
        pageData.pageLoading = true
        updateGridState01()
        post({
          url: 'wms/warehouse/getWarehousePage',
          data: {
            page: page.value,
            size: size.value,
            warehouseName: queryData1.warehouseName,
            warehouseCode: queryData1.warehouseCode,
            firmId: queryData1.firm,
            deleteState: '0',
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
              gridOption.value.setRowData(data.list)
              pagination.setTotalSize(data.total)
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const table1 = useTable()
      const rowKey = useRowKey('id')
      //假数据后期需要修改
      // const dataList = reactive({
      //     list:[{
      //         id:1,
      //         code:1,
      //         mercery_name:'掌紫元',
      //         remark:"WH22101800000002",
      //         remark_1:'裁断中仓',
      //         remark_2:'佛山',
      //         remark_3:'勇哥',
      //         remark_4:'110'
      //     }]
      // })
      let qrModal = ref<ModalDialogType | null>(null)
      const qrData = reactive({
        ckName: '',
        gcName: '',
        code: '',
        ckCode: '',
        ckType: '',
        jsjia: '',
      })
      const openQRcode = (item: any) => {
        console.log(item)
        qrData.gcName = item.firm
        qrData.ckName = item.warehouseName
        qrData.ckCode = item.warehouseCode
        qrData.ckType = item.warehouseTypeName
        qrData.jsjia = item.pricingWay
        qrData.code = JSON.stringify({
          id: item.id,
          firmId: item.firmId,
          warehouseCode: item.warehouseCode,
          warehouseTypeId: item.warehouseTypeId,
        })
        qrModal.value?.toggle()
      }
      // 序号	所属工厂	仓库编码	仓库名称	仓库地址	联系人	联系电话	操作
      const tableColumns = useTableColumn([
        {
          title: '公司',
          key: 'firm',
          dataIndex: 'firm',
          width: 150,
        },
        {
          title: '仓库编号',
          key: 'warehouseCode',
          dataIndex: 'warehouseCode',
          width: 150,
        },
        {
          title: '仓库类型',
          key: 'warehouseTypeName',
          dataIndex: 'warehouseTypeName',
          width: 150,
        },
        {
          title: '仓库名称',
          key: 'warehouseName',
          dataIndex: 'warehouseName',
          width: 150,
        },
        {
          title: '计件方式',
          key: 'pricingWay',
          dataIndex: 'pricingWay',
          width: 150,
        },
        {
          title: '库存警戒',
          key: 'inventoryAlert',
          dataIndex: 'inventoryAlert',
          width: 150,
        },
        {
          title: '吨料存放成本/日',
          key: 'depositCost',
          dataIndex: 'depositCost',
          width: 150,
        },
        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
          width: 150,
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 150,
        },
        {
          title: '修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 150,
        },
        {
          title: '操作',
          key: 'edit',
          dataIndex: 'edit',
          slotName: 'edit',
          width: 150,
          fixed: 'right',
        },
      ])
      const columns = [
        {
          title: '布笼名称',
          dataIndex: 'shelveName',
          slotName: 'shelveName',
        },
        {
          title: '布笼自定义代号',
          dataIndex: 'shelveCode',
          slotName: 'shelveCode',
        },
        {
          title: '储位名称',
          dataIndex: 'storageName',
          slotName: 'storageName',
        },
        {
          title: '储位自定义代号',
          dataIndex: 'storageCode',
          slotName: 'storageCode',
        },
        {
          title: '操作',
          dataIndex: 'save',
          slotName: 'save',
        },
      ]
      const dataLists = ref<dataListType[]>([
        {
          shelveName: '',
          shelveCode: '',
          storageName: '',
          storageCode: '',
        },
      ])
      const pageData: any = reactive({
        gcList: [],
        clothList: [],
        showAdd: false,
        sideTitle: '新增布料基础资料',
        rHeight: 0,
        warehouseName: [],
        warehouseCode: [],
        pageLoading: false,
        UnitList: [],
      })
      // const pageData1 = reactive<{
      //     showAdd: boolean;
      // }>({
      //     showAdd: false,
      // });
      let jjFds = ref<any[]>([])
      const jjFdsFun = () => {
        post({
          url: 'dict/dictTypeDetail/getList',
          data: {
            codeType: 1,
            obsoleteState: 0,
            deleteState: 0,
          },
        }).then((res: any) => {
          if (res.code === 200) {
            jjFds.value = res.data
          } else {
            Message.error(res.message)
          }
        })
      }
      onMounted(() => {
        doRefresh()
        getAllActiveCompany()
        pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
        //弹出层的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight - 100
        }
      })
      const queryData = reactive({
        firm: '',
        clothType: '',
      })
      const queryData1 = reactive({
        warehouseName: '',
        warehouseCode: '',
        firm: '',
      })
      const cklxTable = ref<any[]>([])
      const addHandler = () => {
        ;(queryData1.warehouseCode = ''),
          (queryData1.warehouseName = ''),
          post({
            url: 'wms/warehouseType/getWarehoursTypePara',
            data: {
              obsoleteState: 0,
            },
          }).then(({ data, code }: any) => {
            if (code === 200) {
              cklxTable.value = data
            }
          })
        pageData.showAdd = true
        pageData.sideTitle = '新增仓库'
        for (let item in dataForm) {
          dataForm[item] = ''
        }
      }
      // onMounted(() => {
      //   pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
      //   //弹出层的高
      //   if (pageData.rHeight !== undefined) {
      //     pageData.rHeight = pageData.rHeight
      //   }
      // })
      let gsDatas = ref<any[]>([])
      // 获取公司下拉框
      const getAllActiveCompany = () => {
        post({
          url: 'org/baCompany/getTreeCompanyByUser',
          data: {},
        }).then((result: any) => {
          if (result.code === 200) {
            gsDatas.value = result.data
          } else {
            Message.error(result.message)
          }
        })
      }
      const casOb = ref()
      const getAllActiveCompanys = (val: any) => {
        setTimeout(function () {
          let list = casOb.value.selectViewValue[0]['label'].split('/')
          if (list.length > 1) {
            dataForm.firmName = list[list.length - 1]
          } else {
            dataForm.firmName = list[0]
          }
        }, 100)
      }
      const inputBlur = () => {
        dataForm.warehouseCode = dataForm.warehouseCode.toUpperCase()
      }
      const dataForm: any = reactive({
        id: '',
        firm: '',
        warehouseCode: '',
        warehouseName: '',
        pricingWay: '',
        remark: '',
        deleteState: '',
        createName: '',
        createTime: '',
        updateName: '',
        updateTime: '',
        obsoleteState: '',
        warehouseTypeName: '',
        extendCode: '',
        warehouseTypeId: '',
        tg: '',
        firmName: '',
        firmId: 0,
        salesWarehouseId: '',
        inventoryAlert: 0,
        depositCost: 0,
      })
      const formRef = ref<FormInstance>()
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            dataForm.warehouseTypeName = dataForm.tg.split('-')[0]
            dataForm.warehouseTypeId = Number(dataForm.tg.split('-')[1])
            if (pageData.sideTitle == '新增仓库') {
              post({
                url: 'wms/warehouse/addWarehouse',
                data: [
                  {
                    firm: dataForm.firmName,
                    warehouseCode: dataForm.warehouseCode,
                    warehouseName: dataForm.warehouseName,
                    pricingWay: dataForm.pricingWay,
                    remark: dataForm.remark,
                    warehouseTypeName: dataForm.warehouseTypeName,
                    warehouseTypeId: dataForm.warehouseTypeId,
                    firmId: dataForm.firmId,
                    salesWarehouseId: Number(dataForm.salesWarehouseId),
                    inventoryAlert: dataForm.inventoryAlert,
                    depositCost: dataForm.depositCost,
                  },
                ],
              }).then((res: any) => {
                if (res.code === 200) {
                  for (let i in dataForm) {
                    dataForm[i] = ''
                  }
                  formRef.value?.resetFields()
                  doRefresh()
                  pageData.showAdd = false
                  Message.success({
                    content: '添加成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
            } else if (pageData.sideTitle == '修改仓库') {
              post({
                url: 'wms/warehouse/updateWarehouse',
                data: [
                  {
                    id: dataForm.id,
                    firmId: dataForm.firmId,
                    firm: dataForm.firmName,
                    warehouseCode: dataForm.warehouseCode,
                    warehouseName: dataForm.warehouseName,
                    pricingWay: dataForm.pricingWay,
                    remark: dataForm.remark,
                    warehouseTypeId: dataForm.warehouseTypeId,
                    warehouseTypeName: dataForm.warehouseTypeName,
                    salesWarehouseId: Number(dataForm.salesWarehouseId),
                    inventoryAlert: dataForm.inventoryAlert,
                    depositCost: dataForm.depositCost,
                  },
                ],
              }).then((res: any) => {
                if (res.code === 200) {
                  for (let i in dataForm) {
                    dataForm[i] = ''
                  }
                  formRef.value?.resetFields()
                  doRefresh()
                  pageData.showAdd = false
                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
            }
          }
        })
      }

      const sideNo = () => {
        pageData.showAdd = false
      }
      var id = ''
      const editHandler = (key: any) => {
        getAllActiveCompany2()
        dataForm.firmId = key.firmId
        dataForm.firmName = key.firm
        dataForm.warehouseName = key.warehouseName
        dataForm.tg = key.warehouseTypeName
        dataForm.remark = key.remark
        dataForm.warehouseCode = key.warehouseCode
        dataForm.pricingWay = key.pricingWay
        dataForm.warehouseTypeId = key.warehouseTypeId
        dataForm.salesWarehouseId = key.salesWarehouseId.toString()
        dataForm.inventoryAlert = key.inventoryAlert
        dataForm.depositCost = key.depositCost
        dataForm.id = key.id
        pageData.showAdd = true
        pageData.sideTitle = '修改仓库'
        id = key.id
        selDictAll()
      }
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          return
        }
        let asuiArray: any = []
        gridOption.value.getSelectedRows().forEach((item: any) => {
          asuiArray.push({
            id: item.id,
          })
        })
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            post({
              url: 'wms/warehouse/delWarehouse',
              data: asuiArray,
            }).then(({ code, data, message }: any) => {
              if (code === 200) {
                doRefresh()
                pageData.showAdd = false
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })
              } else {
                Message.error({
                  content: message,
                  duration: 5000,
                })
              }
            })
          },
        })
      }
      const print = () => {
        printJS({
          printable: 'settings',
          type: 'html',
          targetStyles: ['*'],
        })
      }
      const gbModal = () => {
        qrModal.value?.toggle()
      }
      const selectHandler = () => {
        page.value = 1
        doRefresh()
      }
      const visible = ref(false)
      const handleOk = () => {
        visible.value = !visible.value
      }
      const handleCancel = () => {
        visible.value = !visible.value
      }
      let keyList = {
        keyFrim: '',
        keyId: 0,
      }
      const addHandler1 = () => {
        dataLists.value.push({
          shelveName: '',
          shelveCode: '',
          storageName: '',
          storageCode: '',
        })
      }
      const bcCw = (key: any) => {
        let infoLists = {
          shelveName: key.shelveName,
          storgeName: key.storageName,
          shelveId: null,
        }
        console.log(infoLists)
        post({
          url: 'wms/warehouse/addShelveStorage',
          data: {
            firm: keyList.keyFrim,
            warehouseId: Number(keyList.keyId),
            infoList: [infoLists],
          },
        })
          .then(({ data, code, message }: any) => {
            if (code === 200) {
              Message.success('新增成功')
            } else {
              Message.error(message)
            }
          })
          .catch(console.log)
      }
      const options = ref<any>(pageData.warehouseName)
      const options1 = ref<any>(pageData.warehouseCode)
      const loading = ref(false)
      const loading1 = ref(false)
      const handleSearch1 = (value: any) => {
        if (value) {
          const ob = { warehouseCode: value }
          loading1.value = true
          window.setTimeout(() => {
            selCxAll1(ob)
            options1.value = pageData.warehouseCode
            loading1.value = false
          }, 100)
        } else {
          options.value = []
        }
      }

      function selCxAll(val: any) {
        post({
          url: 'wms/warehouse/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            console.log(data)
            pageData.warehouseName = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      function selCxAll1(val: any) {
        post({
          url: 'wms/warehouse/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            console.log(data)
            pageData.warehouseCode = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const handleSearch1s = () => {
        post({
          url: 'wms/warehouse/getFieldValue',
          data: {
            warehouseCode: '',
          },
        }).then(({ data, code }: any) => {
          if (code === 200) {
            console.log(data)
            pageData.warehouseCode = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }
      const handleSearchs = () => {
        if (queryData1.firm == '') {
          pageData.warehouseName = []
          Message.warning('请先选择公司')
          return
        }
        post({
          url: 'wms/warehouse/getWarehouseByPara',
          data: {
            firmId: queryData1.firm,
            virtuallyState: 0,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            pageData.warehouseName = res.data
          } else {
            Message.error(res.message)
          }
        })
      }

      const queryClearChange = () => {
        pageData.warehouseName = []
        queryData1.warehouseName = ''
      }
      const exports = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.warning('请先勾选')
          return
        } else {
          //将表头拼接出来
          let head =
            '<th>公司</th><th>仓库编号</th><th>仓库类型</th><th>仓库名称</th><th>计件方式</th><th>备注</th><th>创建人</th><th>创建时间</th><th>修改人</th><th>修改时间</th>'
          //拿到当前表格数据与勾选的行做筛选

          let nowRow = table.dataList.filter(function (o) {
            return (
              gridOption.value
                .getSelectedRows()
                .map((o: any) => {
                  return o.id
                })
                .indexOf(o['id']) !== -1
            )
          })
          let body = ''
          nowRow.forEach(function (o) {
            body += '<tr><td>' + o['firm'] + '</td>'
            body += '<td>' + o['warehouseCode'] + '</td>'
            body += '<td>' + o['warehouseTypeName'] + '</td>'
            body += '<td>' + o['warehouseName'] + '</td>'
            body += `<td>${o['pricingWay']}</td>`
            body += `<td>${o['remark']}</td>`
            body += '<td>' + o['createName'] + '</td>'
            body += '<td>' + o['createTime'] + '</td>'
            body += '<td>' + o['updateName'] + '</td>'
            body += '<td>' + o['updateTime'] + '</td>'
            body += '</tr>'
          })
          tableToXlsx(head, '仓库', body)
          console.log(table)
        }
      }

      function tableToXlsx(head: any, filename: any, body: any) {
        const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

        const a = document.createElement('a')
        a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
        a.download = filename
        a.click()
        document.removeChild(a)
      }

      const isChiese = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值不能包含中文！')
          }
          resolve()
        })
      }
      const headerShow = ref<boolean>(true)
      //初始化仓库
      const cshck = () => {
        pageData.pageLoading = true
        get({
          url: 'wms/warehouse/initWareHouseByFirm',
        })
          .then((res: any) => {})
          .finally(() => {
            pageData.pageLoading = false
          })
      }
      const gsDatas2 = ref<any[]>([])
      const getAllActiveCompany2 = () => {
        post({
          url: 'org/baCompany/getTreeCompanyByUser',
          data: {},
        }).then((result: any) => {
          if (result.code === 200) {
            gsDatas2.value = result.data
          } else {
            Message.error(result.message)
          }
        })
      }
      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
      }
      let tc: any[] = tableColumns.map((o: any) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          width: 150,
        }
        if (o.slotName === 'edit') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 210
          obj['cellRenderer'] = {
            template: `
                    <a-space>
                        <a-button v-if="e" type="primary" size="mini" status="warning" @click="a1">
                            <template #icon>
                                <icon-edit />
                            </template>
                            修 改
                        </a-button>
                        <a-button v-if="e1" status="success" size="mini" @click="a2">查看二维码</a-button>
                            </a-space>

                    `,
            setup(props: any) {
              const isDtas = ref(props.params.data)
              const a1 = () => {
                editHandler(props.params.data)
              }
              const a2 = () => {
                openQRcode(props.params.data)
              }
              return {
                a1,
                a2,
                isDtas,
                e: permissionStore.hasPermisson('ck.xg'),
                e1: permissionStore.hasPermisson('ck.ckewm'),
              }
            },
          }
        }
        return obj
      })

      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      //下拉框查询
      function selDictAll() {
        post({
          url: '/dict/dictTypeDetail/getListByCodeType?codeType=28',
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.UnitList = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }
      tc = a.concat(tc)
      const localeText1: any = ref(localeText)
      const pagingList1: any = ref(pagingList)
      const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
        saveOrUpdateGridState01('WarehouseSettings-1', gridOption, colState, tc)
      const onColumnMoved = () => {
        saveGridState01()
      }
      const onColumnResized = () => {
        saveGridState01()
      }
      const onColumnVisible = () => {
        saveGridState01()
      }
      return {
        saveOrUpdateGridState01,
        saveGridState01,
        updateGridState01,
        onColumnMoved,
        onColumnResized,
        onColumnVisible,
        colState,
        pagingList1,
        localeText1,
        change1,
        PageSize,
        total,
        page,
        size,
        tc,
        defaultColDef,
        gridReady,
        gridOption,
        getAllActiveCompany2,
        gsDatas2,
        cshck,
        jjFdsFun,
        headerShow,
        selDictAll,
        isChiese,
        handleSearchs,
        handleSearch1s,
        jjFds,
        exports,
        bcCw,
        addHandler1,
        dataLists,
        columns,
        // sideOk1,
        // sideNo1,
        // pageData1,
        table1,
        // editHandler1,
        handleCancel,
        handleOk,
        visible,
        selectHandler,
        cklxTable,
        gbModal,
        print,
        editHandler,
        sideNo,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        qrModal,
        qrData,
        openQRcode,
        queryData1,
        loading,
        loading1,
        // handleSearch,
        handleSearch1,
        inputBlur,
        gsDatas,
        getAllActiveCompany,
        getAllActiveCompanys,
        casOb,
        queryClearChange,
        permissionStore,
      }
    },
    components: { Toolbar, QrcodeVue, ModalDialog,  },
  }
</script>
<style scoped lang="less">
  .cwTitle {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .selectCc {
    width: 100%;
    text-align: right;
    margin-right: 20px;
    margin-bottom: 10px;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }

  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }
</style>
